﻿using System.Collections;
using System.Text;
using System.Collections.Generic;
using UnityEngine;

//渲染逻辑帧
public class GameData
{    
    public string MyID;
    public int MyRoomID = -1;
    public int JoinedRoomID = -1;
    public StringBuilder ChatContent = new StringBuilder("");    
    public class PlayerData
    {        
        public int Progress;
        public Vector3 Pos;
        public Quaternion Dir;
        public ActorController ac;
        public RecInput pi;

        public PlayerData()
        {
            Pos = Vector3.zero;
            Dir = Quaternion.identity;
        }
    }

    public class RoomListWrapper
    {
        public List<GameData.Room> Rooms;
        public RoomListWrapper()
        {
            Rooms = new List<GameData.Room>();
        }
    }

    [System.Serializable]
    public class Room
    {
        public ulong RoomID;
        public string OwnerID;
        public List<string> Players;
        public Room() {
            RoomID = 0;
            Players = new List<string>();
        }
    }    

    public List<Room> Rooms;
    public Room MyRoom;
    public Room JoinedRoom;
    public Dictionary<string, PlayerData> Players = new Dictionary<string, PlayerData>();

    public void Reset()
    {
        Players.Clear();
    }
}

public class GameLogic
{

    public GameData Data = new GameData();
    public ActorController ac;
    public RecInput pi;

    public void Reset()
    {
        Data.Reset();
    }

    public GameData.PlayerData GetMyData()
    {
        return Data.Players[Data.MyID];
    }

    public void JoinRoom(string id)
    {
        var d = new GameData.PlayerData();
        d.Pos = new Vector3(Random.RandomRange(0,5), Random.RandomRange(0,5), 1);
        Data.Players[id] = d;
    }

    public void SetProgress(string id,int progress)
    {
        Data.Players[id].Progress = progress;
    }    

    public void ProcessFrameData(pb.FrameData msg)
    {
        if (null == msg)
        {
            return;
        }
        if (null != msg.InputList)
        {
            foreach (var f in msg.InputList)
            {
                PlayerCmd(f);
            }
        }
        
    }

    public void PlayerCmd(pb.InputData cmd)
    {
        
        GameData.PlayerData data = null;        
        if (!Data.Players.TryGetValue(cmd.Id, out data))
        {
            return;
        }
        var playID = cmd.Id;
        Debug.Log(playID);
        var pi = Data.Players[playID].pi;
        var ac = Data.Players[playID].ac;        
        pi.Dright = cmd.Dright;
        pi.Dup = cmd.Dup;
        pi.Jup = cmd.Jup;
        pi.Jright = cmd.Jright;
        pi.CalDmagDvec(ac.transform);
        ac.DoUpdate(pi);
        
        Debug.Log("Do Update");        
    }
}
